// index.ts - 立体救援首页
const app = getApp<IAppOption>()

interface RescueType {
  id: string
  name: string
  icon: string
  color: string
}

Component({
  data: {
    // 救援类型数据
    rescueTypes: [
      { id: 'ambulance', name: '救护车', icon: '🚑', color: '#FF5722' },
      { id: 'train', name: '高铁转运', icon: '🚄', color: '#2196F3' },
      { id: 'plane', name: '民用航班', icon: '✈️', color: '#FF9800' },
      { id: 'medical_plane', name: '医疗飞机', icon: '🏥', color: '#9C27B0' },
      { id: 'helicopter', name: '直升机', icon: '🚁', color: '#4CAF50' }
    ] as RescueType[],
    
    // 选中的救援类型
    selectedRescueType: '',
    
    // 位置信息
    startLocation: '',
    endLocation: '',
    
    // 时间选择
    timeRange: [
      ['立即用车', '预约时间'],
      ['2024-01-15', '2024-01-16', '2024-01-17'],
      ['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00']
    ],
    timeIndex: [0, 0, 6],
    selectedTime: '2022-09-18 12:00',
    
    // 紧急程度
    urgencyLevel: 'low',
    
    // 乘车人数
    passengerCount: 1,
    
    // 下单类型
    orderType: 'self',
    
    // 手机号码
    phoneNumber: '',
    verifyBtnText: '获取验证码',
    
    // 表单验证
    canSubmit: false,
  },
  
  methods: {
    /**
     * 选择救援类型
     */
    selectRescueType(e: WechatMiniprogram.BaseEvent) {
      const type = e.currentTarget.dataset.type
      this.setData({
        selectedRescueType: type
      })
      console.log('选择救援类型:', type)
      
      // 显示成功提示
      wx.showToast({
        title: '已选择救援类型',
        icon: 'success',
        duration: 1000
      })
    },
    
    /**
     * 选择起始位置
     */
    selectStartLocation() {
      const that = this
      wx.chooseLocation({
        success(res) {
          console.log('起始位置:', res)
          that.setData({
            startLocation: res.name || res.address
          })
        },
        fail() {
          // 如果用户未授权位置，可以手动输入
          wx.showModal({
            title: '位置权限',
            content: '需要获取您的位置信息来提供救援服务',
            success(modalRes) {
              if (modalRes.confirm) {
                that.manualInputLocation('start')
              }
            }
          })
        }
      })
    },
    
    /**
     * 选择目的地位置
     */
    selectEndLocation() {
      const that = this
      wx.chooseLocation({
        success(res) {
          console.log('目的地:', res)
          that.setData({
            endLocation: res.name || res.address
          })
        },
        fail() {
          that.manualInputLocation('end')
        }
      })
    },
    
    /**
     * 手动输入位置
     */
    manualInputLocation(type: 'start' | 'end') {
      const title = type === 'start' ? '请输入起始地点' : '请输入目的地'
      wx.showModal({
        title: title,
        editable: true,
        placeholderText: '请输入地址',
        success: (res) => {
          if (res.confirm && res.content) {
            if (type === 'start') {
              this.setData({
                startLocation: res.content
              })
            } else {
              this.setData({
                endLocation: res.content
              })
            }
          }
        }
      })
    },
    
    /**
     * 时间选择
     */
    onTimeChange(e: WechatMiniprogram.BaseEvent) {
      const values = e.detail.value
      this.setData({
        timeIndex: values
      })
      
      const timeRange = this.data.timeRange
      let selectedTime = ''
      
      if (values[0] === 0) {
        selectedTime = '立即用车'
      } else {
        selectedTime = `${timeRange[1][values[1]]} ${timeRange[2][values[2]]}`
      }
      
      this.setData({
        selectedTime: selectedTime
      })
    },
    
    /**
     * 选择紧急程度
     */
    selectUrgency(e: WechatMiniprogram.BaseEvent) {
      const level = e.currentTarget.dataset.level
      this.setData({
        urgencyLevel: level
      })
    },
    
    /**
     * 选择乘车人数
     */
    selectPassengerCount(e: WechatMiniprogram.BaseEvent) {
      const count = parseInt(e.currentTarget.dataset.count)
      this.setData({
        passengerCount: count
      })
    },
    
    /**
     * 选择下单类型
     */
    selectOrderType(e: WechatMiniprogram.BaseEvent) {
      const type = e.currentTarget.dataset.type
      this.setData({
        orderType: type
      })
    },
    
    /**
     * 输入手机号
     */
    onPhoneInput(e: WechatMiniprogram.BaseEvent) {
      const phone = e.detail.value
      this.setData({
        phoneNumber: phone
      })
      
      // 验证表单是否可以提交
      this.checkFormValid()
    },
    
    /**
     * 发送验证码
     */
    sendVerifyCode() {
      const phone = this.data.phoneNumber
      
      if (!phone || phone.length !== 11) {
        wx.showToast({
          title: '请输入正确手机号',
          icon: 'none'
        })
        return
      }
      
      // 模拟发送验证码
      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      })
      
      // 倒计时
      let countdown = 60
      this.setData({
        verifyBtnText: `${countdown}s后重发`
      })
      
      const timer = setInterval(() => {
        countdown--
        if (countdown > 0) {
          this.setData({
            verifyBtnText: `${countdown}s后重发`
          })
        } else {
          clearInterval(timer)
          this.setData({
            verifyBtnText: '获取验证码'
          })
        }
      }, 1000)
    },
    
    /**
     * 检查表单是否有效
     */
    checkFormValid() {
      const { startLocation, endLocation, phoneNumber, selectedRescueType } = this.data
      
      const isValid = !!(startLocation && endLocation && phoneNumber && selectedRescueType && phoneNumber.length === 11)
      
      this.setData({
        canSubmit: isValid
      })
    },
    
    /**
     * 提交救援申请
     */
    submitRescueRequest() {
      // 检查表单
      if (!this.data.canSubmit) {
        const missing = []
        if (!this.data.selectedRescueType) missing.push('救援类型')
        if (!this.data.startLocation) missing.push('起始地点')
        if (!this.data.endLocation) missing.push('目的地')
        if (!this.data.phoneNumber) missing.push('手机号码')
        
        wx.showModal({
          title: '信息不完整',
          content: `请填写：${missing.join('、')}`,
          showCancel: false
        })
        return
      }
      
      // 显示加载提示
      wx.showLoading({
        title: '提交中...'
      })
      
      // 构建救援请求数据
      const rescueRequest = {
        type: this.data.selectedRescueType,
        startLocation: this.data.startLocation,
        endLocation: this.data.endLocation,
        selectedTime: this.data.selectedTime,
        urgencyLevel: this.data.urgencyLevel,
        passengerCount: this.data.passengerCount,
        orderType: this.data.orderType,
        phoneNumber: this.data.phoneNumber,
        submitTime: new Date().toISOString()
      }
      
      console.log('救援申请数据:', rescueRequest)
      
      // 模拟API调用
      setTimeout(() => {
        wx.hideLoading()
        
        wx.showModal({
          title: '申请成功',
          content: '您的救援申请已提交，我们将尽快为您匹配救援资源，请保持手机畅通。',
          showCancel: false,
          success: () => {
            // 跳转到状态跟踪页面
            wx.navigateTo({
              url: '/pages/rescue/rescue?requestId=' + Date.now()
            })
          }
        })
      }, 2000)
    }
  },
  
  /**
   * 页面加载时
   */
  onLoad() {
    console.log('立体救援首页加载')
    
    // 获取当前位置作为默认起始位置
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('当前位置:', res)
        // 可以根据经纬度逆地址解析获取地址名称
      },
      fail: () => {
        console.log('获取位置失败，用户可能未授权')
      }
    })
  }
})
